package cn.zhaoyuening.leasecloud.common.dao.impl;

import cn.zhaoyuening.leasecloud.common.dao.BaseDao;
import cn.zhaoyuening.leasecloud.common.utils.page.PageQueryHibernateCallback;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;


/**
 * Created by zhao on 17-1-10.
 */
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

    private Class entityClass =
            (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    @Autowired
    public void setMySessionFactory(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }

    @Override
    @Transactional(readOnly = false)
    public void save(T t) {
        getHibernateTemplate().save(t);
    }

    @Override
    public void delete(T t) {
        getHibernateTemplate().delete(t);
    }

    @Override
    public T findById(Serializable id) {
        T t = (T) getHibernateTemplate().get(entityClass, id);
        return t;
    }

    @Override
    @Transactional(readOnly = false)
    public void addOrEdit(T t) {
        getHibernateTemplate().saveOrUpdate(t);
    }

    @Override
    public List<T> findAll() {
        List<T> list = (List<T>) getHibernateTemplate().find("from " + entityClass.getName());
        return list;
    }

    @Override
    public List<T> findAll(String condition, Object[] params) {
        List<T> list = (List<T>) getHibernateTemplate().find("from " + entityClass.getName()
                + " where 1=1 and " + condition, params);
        return list;
    }

    @Override
    public List<T> findAll(String condition, Object[] params, int startIndex, int pageSize) {
        String hql;
        if (condition == null) {
            hql = "from " + entityClass.getName() ;
        }else{
            hql = "from " + entityClass.getName() + " where 1=1  and " + condition;
        }
        PageQueryHibernateCallback<T> callback = new PageQueryHibernateCallback<T>();
        callback.setHql(hql).setPageSize(pageSize).setParams(params).setStartIndex(startIndex);
        List<T> list = getHibernateTemplate().execute(callback);
        return list;
    }

    @Override
    public long getTotalRecord() {
        String hql = "select count(c) from " + entityClass.getName() + " c";
        List list = getHibernateTemplate().find(hql);
        long totalRecord = (Long) list.get(0);
        return totalRecord;
    }

    public Class getEntityClass() {
        return entityClass;
    }
}
